<?php
namespace app\admin\controller;
class Shop extends Base
{
    //列表
    public function lists(){
        if(is_post()){
            $d = $this->post;
            $map = [];
            if($d['keyword']!='') $map[] = ['and','username|name','like',"%{$d['keyword']}%"];
            $w  = where($map);
            $rs = $this->db->query("select * from shop $w[0] order by id desc".limit($d['page'],$d['limit']), $w[1],'',true);
            if($rs){
                $rule = [
                    'status' => function($v){return c("type.status.{$v}");},
                    'create_time' => 'com_time_format',
                ];
                $data = com_format($rs[0],$rule);
                suc($data,$rs[1]);
            }else{
                suc([],0);
            }
        }
        $this->fetch();
    }

    //添加
    public function add(){
        if(is_post()){
            $d = $this->post;
            $rule = [
                'username'=>'require',
                'name'=>'require',
                'password'=>'require|min:6',
            ];
            $msg = [
                'username.require' => '登陆名称不能为空',
                'name.require' => '店铺名不能为空',
                'password.require' => '密码不能为空',
                'password.min' => '密码不能小于6位',
            ];
            check($rule,$msg,$d);
            $d['create_time'] = time();
            $d['password'] = com_password($d['password']);
            $id = $this->db->insert('shop',$d);
            if ($id) {
                cookie('js_msg','添加成功');
                cookie('js_function','preload');
                return suc();
            }else{
                err('添加失败');
            }
        }
        return $this->fetch();
    }

    //编辑
    public function edit(){
        if(is_post()){
            $d = $this->post;
            $d['update_time'] = time();
            $rule = [
                'username'=>'require',
                'name'=>'require',
            ];
            $msg = [
                'username.require' => '登陆名称不能为空',
                'name.require' => '店铺名不能为空',
            ];
            check($rule,$msg,$d);
            if(isset($d['password'])){
                $d['password'] = com_password($d['password']);
            }else{
                unset($d['password']);
            }
            $id = $this->db->update('shop',$d);
            if ($id) {
                cookie('js_msg','修改成功');
                cookie('js_function','preload');
                return suc();
            }else{
                err('修改失败');
            }
        }
        $id = $this->get['id'];
        $info = $this->db->query("select * from shop where id=?",[$id],1);
        return $this->fetch(['info'=>$info]);
    }
    //删除
    public function del(){
        if(is_post()){
            $d = $this->post;
            $this->db->delete('shop',$d['id']);
            cookie('js_msg','删除成功');
            cookie('js_function','close|reload');
            return suc();
        }
    }
}
